package com.newcapce.network;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {
    public static void main(String[] args) throws IOException {
        //所有的网络通信基于socket
        //ip(标识主机)+port(标识应用程序)
        ServerSocket serverSocket = new ServerSocket(11111);
        System.out.println("服务已启动,等待客户端连接....");
        //等待客户端连接
        Socket socket = serverSocket.accept();
        System.out.println("客户端连接成功:"+socket.getRemoteSocketAddress());
        //收发客户端数据.......

        DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
        DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
        new Thread(){
            @Override
            public void run() {
                while (true){
                    String str = null;
                    try {
                        str = dataInputStream.readUTF();
                        System.out.println("服务端收到:"+str);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
//        String str = dataInputStream.readUTF();
//        System.out.println(str);

        Scanner scanner = new Scanner(System.in);
        while(true){
            String sendStr = scanner.nextLine();
            dataOutputStream.writeUTF(sendStr);
            dataOutputStream.flush();
        }
    }
}
